package com.goldgov.code.template.point;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.util.AntPathMatcher;

public class PointMapping{

	private Map<String,List<CodePoint>> pointMap = new HashMap<>();
	
	private AntPathMatcher matcher = new AntPathMatcher();
	
	public List<CodePoint> codePoint(String mappinng){
		List<CodePoint> list;
		if(pointMap.containsKey(mappinng)) {
			list = pointMap.get(mappinng);
		}else {
			list = new ArrayList<>();
			pointMap.put(mappinng,list);
		}
		return list;
	}
	
	public List<CodePoint> getMappingPoint(String templateName) {
		List<CodePoint> result = new ArrayList<>();
		Iterator<String> keyIterator = pointMap.keySet().iterator();
		while(keyIterator.hasNext()) {
			String mappinng = keyIterator.next();
			if(matcher.match(mappinng, templateName)) {
				result.addAll(pointMap.get(mappinng));
			}
		}
		
		return Collections.unmodifiableList(result);
	}
	
	public boolean hasMapping(String mapping) {
		return pointMap.containsKey(mapping);
	}
	
	public Iterator<String> mappingIterator(){
		return pointMap.keySet().iterator();
	}
	
//	public Map<String,List<CodePoint>> merge(PointMapping pointMapping) {
//		Iterator<String> keyIterator = pointMap.keySet().iterator();
//		while(keyIterator.hasNext()){
//			String mapping = keyIterator.next();
//			List<CodePoint> mappingPoint = pointMapping.codePoint(mapping);
//			if(pointMapping.hasMapping(mapping)){
//				List<CodePoint> list = pointMap.get(mapping);
//				list.addAll(mappingPoint);
//			}else {
//				pointMap.put(mapping, mappingPoint);
//			}
//			
//		}
//		return pointMap;
//	}
	
	public Map<String,List<CodePoint>> merge(PointMapping pointMapping) {
		Iterator<String> keyIterator = pointMapping.mappingIterator();
		while(keyIterator.hasNext()){
			String mapping = keyIterator.next();
			List<CodePoint> codePointList = pointMapping.codePoint(mapping);
			if(this.hasMapping(mapping)){
				List<CodePoint> list = pointMap.get(mapping);
				list.addAll(codePointList);
			}else {
				pointMap.put(mapping, codePointList);
			}
			
		}
		return pointMap;
	}
}